<template>
<highlightjs language="JavaScript" highlightAuto top :code="code" />
</template>
<script>
export default {
  setup () {
    const code = `
    setup () {
      const state = reactive({
        map: null,
        overlay: null,
        currentCoordinate: '',
        mapBox: ref(null),
        popup: ref(null)
      })

      onMounted(() => {
        init()
      })

      const init = () => {
        // 弹窗
        state.overlay = new Overlay({
          element: state.popup, // 弹窗标签，在html里
          autoPan: true, // 如果弹窗在底图边缘时，底图会移动
          autoPanAnimation: { // 底图移动动画
            duration: 250
          }
        })
        // 实例化地图
        state.map = new Map({
          target: state.mapBox,
          layers: [
            new Tile({
              name: 'defaultLayer',
              source: new XYZ({
                url: 'http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}'
              })
            })
          ],
          overlays: [state.overlay], // 把弹窗加入地图
          view: new View({
            projection: 'EPSG:4326',
            center: [116.41400, 39.91500],
            zoom: 12 // 地图缩放级别（打开页面时默认级别）
          })
        })
        mapClick()
      }
      // 添加地图点击事件
      const mapClick = () => {
        state.map.on('singleclick', evt => {
          const coordinate = evt.coordinate // 获取坐标
          const hdms = toStringHDMS(toLonLat(coordinate)) // 转换坐标格式
          state.currentCoordinate = hdms // 保存坐标点
          state.overlay.setPosition(coordinate)
        })
      }
      // 关闭弹窗
      const closePopup = () => {
        state.overlay.setPosition(undefined)
        state.currentCoordinate = null
      }
      return {
        ...toRefs(state),
        closePopup
      }
    },
    `
    return {
      code
    }
  }
}
</script>
